from django.core.checks import Tags
from django.shortcuts import render
from blog.models import User, Categories, Articles, Tag, Comment
from django.views import View
import json,re, random
from untils.redis import RedisUtils
from untils.myjwt import generate_jwt
from untils.send_code import send_message
from django.http import JsonResponse
from qiniu import Auth
import time
# Create your views here.
class SendSmsView(View):
    def post(self, request):
        try:
            data = json.loads(request.body.decode())
            phone = data.get('phone')
            if not re.match(r'^1[3-9]\d{9}$',phone):
                return JsonResponse({'message':'手机号格式错误'},status=400)
            code = str(random.randint(1000,9999))
            #发短信
            sms_response = send_message(phone,code)
            print('短信响应',sms_response)
            if sms_response.get('statusCode') == '000000':
                RedisUtils.set_sms_code(phone,code)
                return JsonResponse({'message':'短信发送成功'},status=200)
            else:
                print(f'短信发送失败:{sms_response}')
                return JsonResponse({'message':'发送失败'},status=400)
        except Exception as e:
            print(f'视图异常{str(e)}')
            return JsonResponse({'message':'异常了'},status=500)
class RegisterView(View):
    def post(self,  request):
        try:
            data = json.loads(request.body.decode())
            phone = data.get('phone')
            password = data.get('password')
            code = data.get('code')
            if not all([phone,code,password]):
                return JsonResponse({'message':'信息填写不完整'},status=400)
            if not re.match(r'^1[3-9]\d{9}$',phone):
                return JsonResponse({'message':'手机号格式错误'},status=400)
            if User.objects.filter(phone=phone).exists():
                return JsonResponse({'message':'该手机号已存在用户'},status=400)
            stored_code = RedisUtils.get_sms_code(phone)
            if not stored_code:
                return JsonResponse({'message':'验证码已过期'},status=400)
            if stored_code != code:
                return JsonResponse({'message':'验证码错误'},status=400)
            RedisUtils.del_sms_code(phone)
            user = User(phone=phone)
            user.set_password(password)
            user.save()
            return JsonResponse({'message':'注册成功'},status=200)
        except Exception as e:
            return JsonResponse({'message':str(e)},status=500)

class LoginView(View):
    def post(self, request):
        try:
            data = json.loads(request.body.decode())
            login_type = data.get('login_type')
            phone = data.get('phone')
            if not re.match(r'^1[3-9]\d{9}$', phone):
                return JsonResponse({'message': '手机号格式错误'}, status=400)
            try:
                user = User.objects.filter(phone=phone).first()
            except User.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=404)
            if login_type == 'password':
                password = data.get('password')
                if not password:
                    return JsonResponse({'message': '密码不能为空'}, status=400)
                if not user.check_password(password):
                    return JsonResponse({'message': '密码错误'}, status=400)
            elif login_type == 'code':
                code = data.get('code')
                if not code:
                    return JsonResponse({'message': '验证码不能为空'}, status=400)
                stored_code = RedisUtils.get_sms_code(phone)
                if not stored_code:
                    return JsonResponse({'message': '验证码已过期'}, status=400)
                if stored_code != code:
                    return JsonResponse({'message': '验证码错误'}, status=400)
                RedisUtils.del_sms_code(phone)
            payload = {'user_id': user.id}
            token = generate_jwt(payload)
            return JsonResponse({'message': '登录成功', 'token': token}, status=200)
        except Exception as e:
            return JsonResponse({'message': str(e)}, status=400)

class AddMessageView(View):
    def post(self, request):
        user_id = request.user_id
        if not user_id:
            return JsonResponse({'message':'用户未认证'}, status=401)
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'message':'用户不存在'},status=404)
        data = json.loads(request.body.decode())
        username = data.get('username')
        avatar = data.get('avatar')
        email = data.get('email')
        phone = user.phone
        user.username = username
        user.avatar = avatar
        user.email = email
        user.save()
        return JsonResponse({'message':'用户信息更新成功','data':{
            'username': username,
            'avatar': avatar,
            'email': email,
            'phone': phone
        }}, status=200)
    def get(self,request):
        user_id = request.user_id
        if not user_id:
            return JsonResponse({'message': '用户未认证'}, status=401)
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'message': '用户不存在'}, status=404)
        return JsonResponse({'username':user.username,'avatar':user.avatar,'email':user.email},status=200)
    def put(self, request):  # 新增PUT方法（更新用户信息）
        print("PUT请求体:", request.body)  # 新增日志
        user_id = request.user_id
        if not user_id:
            return JsonResponse({'message': '用户未认证'}, status=401)
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'message': '用户不存在'}, status=404)
        data = json.loads(request.body.decode())
        # 仅更新头像（可根据需求扩展其他字段）
        print("解析后的数据:", data)  # 新增日志
        if 'avatar' not in data:
            return JsonResponse({'message': '缺少avatar参数'}, status=400)  # 明确错误原因
        user.avatar = data['avatar']
        user.save()
        return JsonResponse({'message': '头像更新成功', 'data': {'avatar': user.avatar}}, status=200)

class UpdateUserView(View):
    def post(self, request):
        user_id = request.user_id
        if not user_id:
            return JsonResponse({'message': '用户未认证'}, status=401)
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'message': '用户不存在'}, status=404)
        data = json.loads(request.body.decode())
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        confirm_new_password = data.get('confirm_new_password')

        if not all([old_password, new_password, confirm_new_password]):
            return JsonResponse({'message': '请填写完整数据'}, status=400)

        if new_password != confirm_new_password:
            return JsonResponse({'新的密码和确认密码不一致'},status=400)

        if not user.check_password(old_password):
            return JsonResponse({'message':'旧密码错误'},status=400)

        if old_password == new_password:
            return JsonResponse({'新旧密码不能重复'},status=400)

        user.set_password(new_password)
        user.save()
        return JsonResponse({'message':'密码修改成功'}, status=200)

class TagView(View):
    def get(self, request):
        tags = Tag.objects.all().values('id', 'title')
        return JsonResponse({'message': "获取所有的标签", 'tags': list(tags)}, status=200)
    def post(self, request):
        data = json.loads(request.body.decode())
        title = data.get('title')
        if not title:
            return JsonResponse({'message': '请输入标签数据'}, status=400)
        if Tag.objects.filter(title=title).first():
            return JsonResponse({'message': '该标签已存在'}, status=400)
        tag = Tag.objects.create(title=title)
        return JsonResponse({'message': '标签创建成功'}, status=200)

class SearchTagView(View):
    def get(self, request):
        title = request.GET.get('title')
        if not title:
            return JsonResponse({'message':'请输入查找数据'},status=400)
        tag = Tag.objects.filter(title=title).first()
        if not tag:
            return JsonResponse({'message':'该标签不存在'}, status=404)
        return JsonResponse({'message':'已查找到该标签', 'data': {'title': tag.title}}, status=200)

class UpdateTagView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        old_title = data.get('old_title')
        new_title = data.get('new_title')
        if not all([old_title, new_title]):
            return JsonResponse({'message':'请填写完整数据'}, status=400)
        tag = Tag.objects.filter(title=old_title).first()
        if not tag:
            return JsonResponse({'message':'该标签不存在'},status=404)
        if Tag.objects.filter(title=new_title).exists():
            return JsonResponse({'新标签名已经存在了'},status=400)
        tag.title = new_title
        tag.save()
        return JsonResponse({'message':'标签修改成功'},status=200)
class DeleteTagView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        title = data.get('title')
        if not title:
            return JsonResponse({'message':'请输入要删除的标签名'},status=400)
        tag = Tag.objects.filter(title=title).first()
        if not tag:
            return JsonResponse({'message': '该标签名不存在'},status=404)
        tag.delete()
        return JsonResponse({'message':'标签删除成功'},status=200)

#用户文章获取
class ArticleListView(View):
    def post(self, request):
        user_id = request.user_id
        if not user_id:
            return JsonResponse({'message': '用户未认证'}, status=401)
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'message': '用户不存在'}, status=404)
        data = json.loads(request.body.decode())
        print('Create Article Data:',data)
        title = data.get('title')
        content = data.get('content')
        intro = data.get('intro')
        category_id = data.get('category_id')
        read = data.get('read')
        like = data.get('like')
        view = data.get('view')
        tag_ids = data.get('tags', [])
        if isinstance(tag_ids, str):
            tag_ids = [int(tid.strip()) for tid in tag_ids.split(',') if tid.strip().isdigit()]
        elif isinstance(tag_ids, list):
            tag_ids = [int(tid) for tid in tag_ids if isinstance(tid, (int ,str)) and str(tid).isdigit()]
        else:
            tag_ids = []
        if not all([title, content, intro, category_id]):
            return JsonResponse({'message':'文章内容不完善'}, status=400)
        try:
            category = Categories.objects.get(id=category_id)
        except Categories.DoesNotExist:
            return JsonResponse({'message': '分类不存在'}, status=404)
        article = Articles.objects.create(
            title=title,
            author=user,
            content=content,
            intro=intro,
            category=category,
            read=read,
            like=like,
            view=view
        )
        valid_tags = []
        for tag_id in tag_ids:
            try:
                tag = Tag.objects.get(id=tag_id)
                valid_tags.append(tag)
                article.tags.add(*valid_tags)
            except Tag.DoesNotExist:
                return JsonResponse({'message': f'标签id{tag_id}不存在'},status=400)
        return JsonResponse({'message': '文章创建成功', 'article_id': article.id}, status=201)

    def get(self, request, article_id=None):
        user_id = request.user_id
        if not user_id:
            return JsonResponse({'message': '用户未认证'}, status=401)
        if article_id:
            try:
                #单个文章查询
                article = Articles.objects.select_related('author').get(id=article_id, author_id=user_id)
                tags = [tag.id for tag in article.tags.all()]
                article_info = {
                    "id": article.id,
                    "title": article.title,
                    "intro": article.intro,
                    "content": article.content,
                    "category": article.category.category,
                    "tags": tags,
                    'read': str(article.read),
                    'like': article.like,
                    'view': article.view,
                    'create_time': article.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'author_username': article.author.username,
                    'author_avatar': article.author.avatar,
                }
                return JsonResponse({'message': '获取文章详情成功', 'article': article_info}, status=200)
            except Articles.DoesNotExist:
                return JsonResponse({'message': '文章不存在'}, status=404)
        else:
            #全部文章查询
            articles = Articles.objects.filter(author_id=user_id).select_related('author')
            article_list = []
            for article in articles:
                tags = [tag.id for tag in article.tags.all()]
                article_info = {
                    "id": article.id,
                    "title": article.title,
                    "intro": article.intro,
                    "content": article.content,
                    "category": article.category.category,
                    "tags": tags,
                    'read': str(article.read),
                    'like': article.like,
                    'view': article.view,
                    'create_time': article.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'author_username': article.author.username,
                    'author_avatar': article.author.avatar
                }
                article_list.append(article_info)
            return JsonResponse({'message': '获取文章列表成功', 'article_list': article_list}, status=200)
    def put(self,request,article_id):
        user_id = request.user_id
        if not user_id:
            return JsonResponse({"message": "用户未认证"}, status=401)
        try:
            article = Articles.objects.get(id=article_id, author_id=user_id)
        except Articles.DoesNotExist:
            return JsonResponse({'message': '文章不存在'}, status=404)
        data = json.loads(request.body.decode())
        print('Update Article Data:', data)  # 添加打印语句
        if 'title' in data:
            article.title = data['title']
        if 'intro' in data:
            article.intro = data['intro']
        if 'content' in data:
            article.content = data['content']
        if 'category_id' in data:
            article.category = Categories.objects.get(id=data['category_id'])
        if 'tags' in data:
            try:
                tag_ids = list(map(int, data['tags']))
                article.tags.set(tag_ids)
            except ValueError:
                return JsonResponse({'message':"标签id需要为整数"}, status=400)
        article.save()
        return JsonResponse({'message': "文章更新成功"}, status=200)

#用户文章删除
class ArticleDeleteView(View):
    def delete(self, request, article_id):
        user_id = request.user_id
        if not user_id:
            return JsonResponse({"message": '用户未认证'}, status=401)
        try:
            article = Articles.objects.get(id=article_id, author_id=user_id)
            article.delete()
            return JsonResponse({'message': '文章删除成功'}, status=200)
        except Articles.DoesNotExist:
            return JsonResponse({'message': '文章不存在'}, status=404)
        except Exception as e:
            return JsonResponse({"message": "删除失败"}, status=500)

class ArticlePublishView(View):
    def get(self, request, article_id=None):
        #详情页
        if article_id:
            try:
                articles = Articles.objects.select_related('author', 'category').prefetch_related('tags').get(id=article_id)
                tags = [{'id': tag.id, 'title': tag.title} for tag in articles.tags.all()]
                article_info = {
                    'id': articles.id,
                    'title': articles.title,
                    'intro': articles.intro,
                    'content': articles.content,
                    'category': articles.category.category,
                    'tags': tags,
                    'read': str(articles.read),
                    'like': articles.like,
                    'view': articles.view,
                    'create_time': articles.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'author': {
                        'username': articles.author.username,
                        'avatar': articles.author.avatar
                    }
                }
                return JsonResponse({'message': '查找成功', 'data': article_info}, status=200)
            except Articles.DoesNotExist:
                return JsonResponse({'message': "文章不存在"}, status=404)
        else:
            #列表
            articles = Articles.objects.select_related('author','category').prefetch_related('tags')
            article_list = []
            for article in articles:
                tags = [tag.id for tag in article.tags.all()]
                article_list.append({
                    'id': article.id,
                    'title': article.title,
                    'intro': article.intro,
                    'category': article.category.category,
                    'create_time': article.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'author':{
                        'username': article.author.username,
                        'avatar': article.author.avatar
                    }
                })
            return JsonResponse({'message':'文章列表','data':article_list}, status=200)

class QiNiuYun(View):
    def get(self, request):
        # 需要填写你的 Access Key 和 Secret Key
        access_key = 'rlk3rxpeBY-hDXmyeR-5cWczEXguhIMiVXLRmc6-'
        secret_key = '0YFTxX3_0-cveWIBcIi5WCe3G7FicA5VScZlTiOa'
        bucket_name = "aixiyyy"
        # 生成上传Token（不指定key，自动生成唯一文件名）
        q = Auth(access_key, secret_key)
        policy ={
            'scope': bucket_name,
            'deadline': int(time.time())+3600,
            'returnBody': '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'  # 可选：返回更多信息
        }
        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name, key=None, policy=policy) # 不指定key，七牛云自动生成文件名
        print("七牛云Token:", token)  # 新增日志
        return JsonResponse({'message': '获取上传的token成功', 'token': token}, status=200)

class ArticleCommentsView(View):
    def get(self, request, article_id):
        try:
            article = Articles.objects.get(id=article_id)
            comments = Comment.objects.filter(article=article).select_related('user')
            comment_list = []
            for comment in comments:
                comment_list.append({
                    'id': comment.id,
                    'content': comment.content,
                    'author': comment.user.username,
                    'create_time': comment.create_time.strftime('%Y-%m-%d %H:%M:%S')
                })
            return JsonResponse({'comments': comment_list}, status=200)
        except Articles.DoesNotExist:
            return JsonResponse({'message': '文章不存在'}, status=404)

    def post(self, request, article_id):
        if not hasattr(request, 'user_id') or not request.user_id:
            return JsonResponse({'message': '用户未登录'}, status=401)
        try:
            article = Articles.objects.get(id=article_id)
            data = json.loads(request.body)
            content = data.get('content')
            if not content:
                return JsonResponse({'message': '评论内容不能为空'}, status=400)
            user = User.objects.get(id=request.user_id)
            comment = Comment.objects.create(
                article=article,
                content=content,
                user=user
            )
            return JsonResponse({
                'id': comment.id,
                'content': comment.content,
                'create_time': comment.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                'author': user.username
            }, status=200)
        except Articles.DoesNotExist:
            return JsonResponse({'message':'文章不存在'}, status=404)
        except User.DoesNotExist:
            return JsonResponse({'message': '用户不存在'}, status=404)